<!-- 故障诊断统计表-->

<template>
    <div class="wrapper">
        <!-- 报表标题组件-->
        <ReportTitle :titleInfo="titleInfo" @handleExport="handleExport" />
        <!-- 报表检索条件组件 -->
        <ReportSearch :loading="loading" :searchFormDatas="searchFormDatas" v-model:searchForm="searchForm"
            @handleSearchForm="handleSearchForm" @handleResetForm="handleResetForm" />
        <!-- 报表表格标题组件-->
        <ReportTableTitle :tableTitle="tableTitle" />
        <!-- 报表表格组件-->
        <ReportTable :loading="loading" :showSummary="true" :tableData="tableData" :pageInfo="pageInfo"
            :summaryData="summaryData" :tableColumnData="tableColumnData" :tableColumnWidthData="tableColumnWidthData" />
        <!-- 报表表格分页组件-->
        <ReportTablePage v-model:pageInfo="pageInfo" @handleSearchForm="handleSearchForm" />
    </div>
</template>

<script setup>
import { ref, reactive, watch, onMounted } from 'vue';
import { ElMessage } from 'element-plus';

import ReportTitle from '@/components/reportTitle/index.vue';
import ReportSearch from '@/components/reportSearch/index.vue';
import ReportTableTitle from '@/components/reportTableTitle/index.vue';
import ReportTable from '@/components/reportTable/index.vue';
import ReportTablePage from '@/components/reportTablePage/index.vue';

import * as local from '@/utils/cache/localStorage';
import * as server from '@/api/modules/technicalDataAnalysis';
import * as cookies from "@/utils/cache/cookies";
import * as basicServer from '@/api/modules/common';

import { faultSearchOptions } from '@/constant/selectOptions';
import { getYesterday } from '@/utils/date';
import { apiFn, deepCopy, getObjectSpan, exportReportFile } from '@/utils/utilFns';

// 报表标题信息
const titleInfo = reactive({
    title: '故障诊断统计表',
    description: ""
});

// 报表表格标题
const defaultTitle = '故障诊断统计表';
const tableTitle = ref(defaultTitle);

// 默认表单数据
const defaultSearchForm = {
    orgIds: local.getItem('defaultOrgIds'),
    dateType: '1',
    timeFrame: [getYesterday(), getYesterday()],
    vehicleModel: '',
    vehicleNumber: [],
    statType: '1',          // 检索方式
	faultType: '',          // 所属模块
	faultLevel: '',         // 故障等级
	driverMode: [],         // 驾驶模式
	productMode: '',        // 生产模式
	versions: [],           // 版本
};

// 默认分页数据
const defaultPageInfo = {
    currentPage: 1,
    pageSize: 20,
    total: 0
};

// 加载状态
const loading = ref(false);

// 表头数据
const tableColumnData = ref([]);

// 表格数据
const tableData = ref([]);

// 表头宽度数据
const tableColumnWidthData = {
    tyDate: '100',
	typeCount_7: '100',
	typeCount_8: '100',
	typeCount_9: '100',
	typeCount_10: '100',
	typeCount_11: '100',
	typeCount_12: '100',
	typeCount_13: '110',
	typeCount_14: '100',
	typeCount_16: '100',
	typeCount_21: '100',
	typeCount_22: '100',
	typeCount_24: '100',
	typeTimes_7: '100',
	typeTimes_8: '100',
	typeTimes_9: '100',
	typeTimes_10: '100',
	typeTimes_11: '100',
	typeTimes_12: '100',
	typeTimes_13: '110',
	typeTimes_14: '100',
	typeTimes_16: '100',
	typeTimes_21: '100',
	typeTimes_22: '100',
	typeTimes_24: '100',
};

// 检索条件数据
const searchFormDatas = ref([
    {
        id: 0,
        type: 'selectTree',
        label: '所属组织',
        prop: 'orgIds',
        options: [],
        api: () => { },
        placeholder: '请选择所属组织',
        rules: [{ required: true, message: '请选择所属组织', trigger: ['blur, change'] }]
    },
    {
        id: 1,
        type: 'dateRangePicker',
        prop: 'timeFrame',
        label: '时间范围',
        options: [],
        api: () => { },
        placeholder: '请选择时间范围',
        rules: [{ required: true, message: '请选择时间范围', trigger: ['change'] }]
    },
    {
        id: 2,
        type: 'select',
        prop: 'statType',
        label: '检索方式',
        clearable: false,
        options: faultSearchOptions,
        api: () => { },
        placeholder: '请选择',
    },
    {
        id: 3,
        type: 'select',
        prop: 'faultType',
        label: '所属模块',
        clearable: false,
        options: [],
        api: () => { },
        placeholder: '请选择',
    },
    {
        id: 4,
        type: 'select',
        prop: 'faultLevel',
        label: '故障等级',
        clearable: false,
        options: [],
        api: () => { },
        placeholder: '请选择',
    },
    {
        id: 5,
        type: 'selectModel',
        prop: 'vehicleModel',
        label: '设备型号',
        options: [],
        api: () => { },
        placeholder: '请选择',
    },
    {
        id: 6,
        type: 'selectNumber',
        prop: 'vehicleNumber',
        label: '设备编号',
        options: [],
        api: () => { },
        placeholder: '请选择',
    },
    {
        id: 7,
        type: 'select',
        prop: 'productMode',
        label: '生产模式',
        clearable: false,
        options: [],
        api: () => { },
        placeholder: '请选择',
    },
    {
        id: 8,
        type: 'selectMulti',
        prop: 'versions',
        label: '程序版本',
        clearable: false,
        options: [],
        api: () => { },
        placeholder: '请选择',
    },
    {
        id: 9,
        type: 'selectMulti',
        prop: 'driverMode',
        label: '驾驶模式',
        clearable: false,
        options: [],
        api: () => { },
        placeholder: '请选择',
    },
]);

// 表单数据
const searchForm = reactive(deepCopy(defaultSearchForm));

// 分页数据
const pageInfo = reactive(deepCopy(defaultPageInfo));

// 汇总数据
const summaryData = ref({});

onMounted(() => {
    getFaultLevelOptions();
    getFaultModuleOptions();
    getProgramVersionOptions();
    getEquipModelOptions();
    getEquipNumberOptions();
    getProductModeOptions();
    getDriveModeOptions()
});

// 所属组织变化监听
watch(() => searchForm.orgIds, () => {
    searchForm.vehicleModel = '';
    searchForm.vehicleNumber = [];
	searchForm.faultType = '';         
	searchForm.faultLevel = '';       
	searchForm.versions = [];   
	
    getFaultLevelOptions();
    getFaultModuleOptions();
    getProgramVersionOptions();
    getEquipModelOptions();
    getEquipNumberOptions();
});

// 设备型号变化监听
watch(() => searchForm.vehicleModel, () => {
    searchForm.vehicleNumber = [];
    getEquipNumberOptions();
});

// 获取故障等级options
const getFaultLevelOptions = () => {
    const params = {
        equal: { orgId: searchForm.orgIds, type: '1' }
    };

    apiFn(basicServer.getFaultLevelList, params)
        .then((res) => {
            const { code, data = [] } = res;
            if (code === '200') {
                searchFormDatas.value[4]['options'] = data
            } 
        }).catch(() => {
            searchFormDatas.value[4]['options'] = [];
        });
};

// 获取故障模块options
const getFaultModuleOptions = () => {
    const params = {
        equal: { orgId: searchForm.orgIds, type: '2' }
    };

    apiFn(basicServer.getFaultModulelList, params)
        .then((res) => {
            const { code, data = [] } = res;
            if (code === '200') {
                searchFormDatas.value[3]['options'] = data
            } 
        }).catch(() => {
            searchFormDatas.value[3]['options'] = [];
        });
};

// 获取程序版本options
const getProgramVersionOptions = () => {
    const params = {
        equal: { orgId: searchForm.orgIds, code: 'sys_process_version_type' }
    };

    apiFn(basicServer.getDicItemsByTypeCode, params)
        .then((res) => {
            const { code, data = [] } = res;
            if (code === '200') {
                searchFormDatas.value[8]['options'] = data
            } 
        }).catch(() => {
            searchFormDatas.value[8]['options'] = [];
        });
};

// 获取驾驶模式options
const getDriveModeOptions = () => {
    const params = {
        equal: { orgId: searchForm.orgIds, code: 'sys_driver_mode' }
    };

    apiFn(basicServer.getDicItemsByTypeCode, params)
        .then((res) => {
            const { code, data = [] } = res;
            if (code === '200') {
                searchFormDatas.value[9]['options'] = data
            } 
        }).catch(() => {
            searchFormDatas.value[9]['options'] = [];
        });
};

// 获取生产模式options
const getProductModeOptions = () => {
    const params = {
        equal: { orgId: searchForm.orgIds, code: 'sys_product_mode' }
    };

    apiFn(basicServer.getDicItemsByTypeCode, params)
        .then((res) => {
            const { code, data = [] } = res;
            if (code === '200') {
                searchFormDatas.value[7]['options'] = data
            } 
        }).catch(() => {
            searchFormDatas.value[7]['options'] = [];
        });
};

// 获取设备型号
const getEquipModelOptions = () => {
    const params = {
        like: { orgId: searchForm.orgIds },
        equal: { vehicleCategory: '1' }
    };

    apiFn(basicServer.getModelList, params)
        .then((res) => {
            const { code, data = [] } = res;
            if (code === '200') {
                searchFormDatas.value[5]['options'] = data
            } else {
                searchFormDatas.value[5]['options'] = [];
            }
        }).catch(() => {
            searchFormDatas.value[5]['options'] = [];
        });
};

// 获取设备编号
const getEquipNumberOptions = () => {
    let params = {
        like: { orgId: searchForm.orgIds },
        equal: { vehicleCategory: '1' }
    };

    if (searchForm.vehicleModel) {
        params['equal']['modelId'] = searchForm.vehicleModel.split("_")[0];
    }

    apiFn(basicServer.getNumberList, params)
        .then((res) => {
            const { code, data = [] } = res;
            if (code === '200') {
                searchFormDatas.value[6]['options'] = data
            } else {
                searchFormDatas.value[6]['options'] = [];
            }
        }).catch(() => {
            searchFormDatas.value[6]['options'] = [];
        });
};

// 获取查询参数
const getParams = () => {
    const { orgIds, dateType, timeFrame, statType, vehicleModel, vehicleNumber, driverMode, productMode, versions, faultType, faultLevel } = searchForm;
    const { pageSize, currentPage } = pageInfo;

    const params = {
        equal: {
            orgId: orgIds,
            dateType,
            startDate: timeFrame[0].replaceAll("-", ""),
            endDate: timeFrame[1].replaceAll("-", ""),
            vin: vehicleNumber.join(','),
			vehicleModel: vehicleModel ? vehicleModel.split('_')[1] : "",
			statType,
			driverMode: driverMode.join(','),
			productMode,
			versions: versions.join(','),
        },
        limit: pageSize,
        page: currentPage,
    };
    
    if (statType === '1') {
		params['equal']['faultType'] = faultType;
	}

	if (statType === '2') {
		params['equal']['faultLevel'] = faultLevel;
	}

    return params;
};

// 获取报表表头
const getTableColumn = () => {
    const params = getParams();
    apiFn(server.getFaultDiagStatisTableColumn, params)
        .then(res => {
            const { code, data = [], resultMsg = '' } = res;
            if (code === '200') {
                tableColumnData.value = data;
                tableTitle.value = resultMsg;
                getTableList();
            } else {
                tableColumnData.value = [];
                tableTitle.value = defaultTitle;
            }
        }).catch(() => {
            tableColumnData.value = [];
            tableTitle.value = defaultTitle;
        })
};

// 获取报表列表内容
const getTableList = () => {
    const params = getParams();
    loading.value = true;
    apiFn(server.getFaultDiagStatisTableList, params)
        .then(res => {
            const { code, data = {}, recordsTotal } = res;
            if (code === '200') {
                const { list = [], chartData = {} } = data;
                if (list.length > 0) {
                    summaryData.value = list.at(-1);
					tableData.value = list.slice(0, list.length - 1);
                } else {
                    summaryData.value = {};
                    tableData.value = [];
                }

                pageInfo.total = recordsTotal;
            }
        }).catch(() => {
            tableData.value = [];
            pageInfo.total = 0;
        }).finally(() => {
            loading.value = false;
        })
};

// 查询
const handleSearchForm = (type) => {
    if (loading.value) return;

    if (type === 'search') {
        Object.keys(defaultPageInfo).forEach(key => {
            if (key in pageInfo) {
                pageInfo[key] = defaultPageInfo[key];
            }
        })
    }
    getTableColumn();
};

// 导出
const handleExport = () => {
    if (!tableData.value.length) {
        ElMessage.warning('无查询数据导出!');
        return;
    }

    const url = window.config.APP_BASE_URL + "report/exportVehicleFaultStat";
    const params = getParams();

    exportReportFile(url, "POST", {
        ElMessage: ElMessage,
        token: cookies.getToken(),
        params: params,
    });
};

// 重置
const handleResetForm = () => {
    Object.keys(searchForm).forEach(key => {
        if (key in defaultSearchForm) {
            searchForm[key] = defaultSearchForm[key];
        }
    });

    Object.keys(defaultPageInfo).forEach(key => {
        if (key in pageInfo) {
            pageInfo[key] = defaultPageInfo[key];
        }
    });

    tableTitle.value = defaultTitle;
    tableColumnData.value = [];
    tableData.value = [];
};
</script>

<style lang="scss" scoped></style>